const express = require('express');
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const { exec } = require('child_process');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 数据库连接
const connection = mysql.createConnection({
  host: '10.11.5.167',
  port: 13306,
  user: 'root',
  password: '123456',
  database: 'my_database'
});

// 首页
app.get('/', (req, res) => {
  res.send(`
    <h2>上传本地视频路径到数据库</h2>
    <form method="POST" action="/upload-path">
      <input type="text" name="videoPath" placeholder="输入的视频" style="width:300px"/>
      <button type="submit">上传</button>
    </form>
    <br>
    <a href="/videos">查看所有视频</a>
    <br>
    <a href="/analyzed-videos">分析后视频列表</a>
  `);
});

// 上传本地视频路径到数据库并异步分析
app.post('/upload-path', (req, res) => {
  const videoPath = req.body.videoPath;
  if (!videoPath || !fs.existsSync(videoPath)) {
    return res.send('视频路径无效或文件不存在');
  }
  connection.query(
    'INSERT INTO videos2 (path) VALUES (?)',
    [videoPath],
    (err, result) => {
      if (err) {
        return res.send('数据库插入失败: ' + err.message);
      }
      // 立即返回
      res.send('上传成功，分析已启动！<br><a href="/">返回</a>');
      // 后台异步分析
      const pyPath = '/home/user3/mmaction2_YF_2/demo/cutted_demo_spatiotemporal_det_slowfast.py';
      const cmd = `python3 ${pyPath} --video "${videoPath}" --config configs/detection/ava/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb.py --checkpoint https://download.openmmlab.com/mmaction/detection/ava/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb_20201217-16378594.pth`;
      exec(cmd, { cwd: '/home/user3/mmaction2_YF_2' }, (error, stdout, stderr) => {
        if (error) {
          console.error('分析失败:', stderr || error.message);
        } else {
          console.log('分析完成:', videoPath);
        }
      });
    }
  );
});

// 展示所有视频列表
app.get('/videos', (req, res) => {
  connection.query('SELECT * FROM videos2', (err, results) => {
    if (err) {
      return res.send('数据库查询失败: ' + err.message);
    }
    let html = '<h2>视频列表</h2><ul>';
    results.forEach(row => {
      html += `<li>
        ${row.path}
        <a href="/play/${row.id}" target="_blank">播放</a>
      </li>`;
    });
    html += '</ul><a href="/">返回</a>';
    res.send(html);
  });
});

// 播放视频及分析结果
app.get('/play/:id', (req, res) => {
  const id = req.params.id;
  connection.query('SELECT * FROM videos2 WHERE id = ?', [id], (err, results) => {
    if (err || results.length === 0) {
      return res.send('未找到视频');
    }
    const videoPath = results[0].path;
    if (!fs.existsSync(videoPath)) {
      return res.send('视频文件不存在');
    }
    // 读取分析结果
    const resultFile = '/home/user3/mmaction2_YF_2/tmp/行为数据统计.csv';
    let analysisResult = '暂无分析结果';
    if (fs.existsSync(resultFile)) {
      const csvContent = fs.readFileSync(resultFile, 'utf-8');
      // CSV转HTML表格
      const lines = csvContent.trim().split('\n');
      let table = '<table border="1" cellpadding="5">';
      lines.forEach((line, idx) => {
        const cells = line.split(',');
        table += '<tr>' + cells.map(cell => `<${idx === 0 ? 'th' : 'td'}>${cell}</${idx === 0 ? 'th' : 'td'}>`).join('') + '</tr>';
      });
      table += '</table>';
      analysisResult = '分析成功<br>' + table;
    }
    res.send(`
      <h2>视频播放</h2>
      <video src="/video-stream/${id}" controls width="600"></video>
      <h3>分析结果</h3>
      ${analysisResult}
      <br><a href="/videos">返回列表</a>
    `);
  });
});

// 视频流接口
app.get('/video-stream/:id', (req, res) => {
  const id = req.params.id;
  connection.query('SELECT * FROM videos2 WHERE id = ?', [id], (err, results) => {
    if (err || results.length === 0) {
      return res.status(404).send('未找到视频');
    }
    const videoPath = results[0].path;
    if (!fs.existsSync(videoPath)) {
      return res.status(404).send('视频文件不存在');
    }
    const stat = fs.statSync(videoPath);
    const fileSize = stat.size;
    const range = req.headers.range;
    if (range) {
      const parts = range.replace(/bytes=/, "").split("-");
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
      const chunksize = (end - start) + 1;
      const file = fs.createReadStream(videoPath, { start, end });
      const head = {
        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Type': 'video/mp4',
      };
      res.writeHead(206, head);
      file.pipe(res);
    } else {
      const head = {
        'Content-Length': fileSize,
        'Content-Type': 'video/mp4',
      };
      res.writeHead(200, head);
      fs.createReadStream(videoPath).pipe(res);
    }
  });
});

// 分析后视频列表
app.get('/analyzed-videos', (req, res) => {
  const analyzedVideoPath = '/home/user3/mmaction2_YF_2/tmp/combined.mp4';
  let html = '<h2>分析后视频列表</h2><ul>';
  if (fs.existsSync(analyzedVideoPath)) {
    html += `<li>
      ${analyzedVideoPath}
      <a href="/play-analyzed" target="_blank">播放分析后视频</a>
    </li>`;
  } else {
    html += '<li>暂无分析后视频</li>';
  }
  html += '</ul><a href="/">返回</a>';
  res.send(html);
});

// 分析后视频播放页面
app.get('/play-analyzed', (req, res) => {
  const analyzedVideoPath = '/home/user3/mmaction2_YF_2/tmp/combined.mp4';
  if (!fs.existsSync(analyzedVideoPath)) {
    return res.send('分析后视频不存在');
  }
  res.send(`
    <h2>分析后视频播放</h2>
    <video src="/analyzed-video-stream" controls width="600"></video>
    <br><a href="/analyzed-videos">返回列表</a>
  `);
});

// 分析后视频流接口
app.get('/analyzed-video-stream', (req, res) => {
  const analyzedVideoPath = '/home/user3/mmaction2_YF_2/tmp/combined.mp4';
  if (!fs.existsSync(analyzedVideoPath)) {
    return res.status(404).send('分析后视频不存在');
  }
  const stat = fs.statSync(analyzedVideoPath);
  const fileSize = stat.size;
  const range = req.headers.range;
  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
    const chunksize = (end - start) + 1;
    const file = fs.createReadStream(analyzedVideoPath, { start, end });
    const head = {
      'Content-Range': `bytes ${start}-${end}/${fileSize}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(206, head);
    file.pipe(res);
  } else {
    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/mp4',
    };
    res.writeHead(200, head);
    fs.createReadStream(analyzedVideoPath).pipe(res);
  }
});

// 启动服务
const PORT = 3310;
app.listen(PORT, () => {
  console.log(`服务已启动：http://localhost:${PORT}`);
});

module.exports = app;